import uuid
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler as OriginRequestHandler

from webutils.layers.connection import ConnectionProxy
from webutils.logging import get_summary, LoggingMixin
from webutils.compat import complex_json

from .mixin import RemoteIPMixin


def genereate_request_id():
    return uuid.uuid4().hex


class RequestHandler(RemoteIPMixin, LoggingMixin, OriginRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.connection = None

    async def prepare(self):
        self.connection = ConnectionProxy(
            self.application,
            log_context=self.log_context,
        )

    def on_finish(self):
        IOLoop.current().add_callback(self.connection.close)
        self.connection = None

    def _request_summary(self):
        origin_summary = super()._request_summary()
        extra_summary = get_summary(self.log_context)
        return f'{origin_summary} {extra_summary}'

    def write_json(self, data, **kwargs):
        kwargs.setdefault('ensure_ascii', False)
        self.set_header('Content-Type', 'application/json')
        return self.write(complex_json.dumps(data, **kwargs))

    def write_response(self, resp, **kwargs):
        return self.write_json(resp, **kwargs)
